<template>
  <div class="main">
    <div class="top">
      <Row>
        <Col ref="wrapRef" v-bind="{ md: 24, lg: 14, xl: 18, xxl: 21 }">
          <ProForm
            labelAlign="right"
            ref="formRef"
            :model="formState"
            :items="items"
            :labelCol="{ span: 8 }"
            :wrapperCol="{ span: 16 }"
            :onValuesChange="onValuesChange"
            :formColLayout="formColLayout()"
          >
          </ProForm>
        </Col>
        <Col v-bind="{ md: 24, lg: 10, xl: 6, xxl: 3 }">
          <Flex justify="end">
            <Space :size="8">
              <b-button icon="search" @click="getInfo(formState)"
                >统计</b-button
              >
              <b-button icon="reset" @click="onReset()">重置</b-button>
            </Space>
          </Flex>
        </Col>
      </Row>
    </div>
    <div class="bottom">
      <div id="bar-chart"></div>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import { computed, nextTick, ref, shallowRef } from 'vue';
import { Col, Flex, Row, Space, Table, TreeSelect } from 'ant-design-vue';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { useFormModal } from '@/hooks/formModal';
import { listToOption, treeToArray } from '@/utils/utils';
import { getDeviceOnlineStatistics } from '@/api/onlineStatistics';
import { reportStore } from '../store';

const {
  refreshStore,
  deviceModeOptions,
  deviceModeEnum,
  getModelOptions,
  getModelEnum,
  projectList,
} = reportStore();

const init = () => {
  refreshStore.timeDelay();
};

init();
const formState = ref<Record<string, any>>({});
const items = computed<ProFormProps['items']>(() => [
  {
    label: '项目名称',
    type: 'input',
    field: 'projectId',
    customRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectList.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          showCheckedStrategy={TreeSelect.SHOW_ALL}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (
              omittedValues.length == treeToArray(projectList.value).length
            ) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    label: '设备类型',
    type: 'select',
    field: 'deviceType',
    props: {
      options: deviceModeOptions.value,
    },
  },
  {
    label: '时间',
    type: 'dateRange',
    field: 'time',
    props: {
      disabledDate: (current: any) => {
        return current && current.isAfter(dayjs().endOf('day'));
      },
    },
  },
]);
const column = 4;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 9 },
    wrapperCol: { span: 20 },
  };
});
const formRef = ref();
const getInfo = async (params: any) => {
  if (!params.startTime || !params.endTime) {
    const start = dayjs().startOf('month').valueOf();
    const end = dayjs().valueOf();
    params.startTime = start;
    params.endTime = end;
  }
  if (params.projectId) {
    params.projectId = params.projectId.join();
  }
  if (params.time) {
    params.startTime = dayjs(params.time[0]).valueOf();
    params.endTime = dayjs(params.time[1]).valueOf();
  }
  const result: any = await getDeviceOnlineStatistics(params);

  nextTick(() => {
    getInit(result.data);
  });
};
getInfo(formState.value);

const onReset = () => {
  formRef.value.resetFields();
  getInfo({});
};

const getInit = (data: any) => {
  let dom = echarts.init(document.getElementById('bar-chart'));
  var LegData = ['在线数', '设备总数'];
  var maxSerData: any = [];
  var minSerData: any = [];
  var XaData: any = [];
  var XaAllData: any = [];
  data.forEach((item: any) => {
    maxSerData.push(item.maxOnline);
    minSerData.push(item.minOnline);
    XaData.push(item.time);
    XaAllData.push(item.total);
  });
  //数据参数

  var option = {
    title: [
      {
        top: '3%',
        text: '最高在线数',
        textStyle: {
          color: '#fff',
        },
      },
      {
        top: '50%',
        text: '最低在线数',
        textStyle: {
          color: '#fff',
        },
      },
    ],

    // tooltip: {
    //     trigger: "axis",
    // },
    grid: [
      {
        top: '8%',
        bottom: '55%',
      },
      {
        top: '55%',
        bottom: '3%',
      },
    ],
    // tooltip: {
    //     trigger: 'axis',
    //     axisPointer: {
    //         type: 'shadow'
    //     },
    // },
    legend: {
      data: LegData,
      right: '15%',
      top: '0',
      textStyle: {
        color: '#fff',
      },
    },
    xAxis: [
      {
        type: 'category',
        data: XaData,
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          // rotate: 45,
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
      },
      {
        gridIndex: 1,
        type: 'category',
        data: XaData,
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          // rotate: 45,
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          //show: false,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(200,200,200,1)', //里面横着的虚线
          },
        },
        axisTick: {
          show: false,
        },
        // data: SerData,
        axisLabel: {
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
      },
      {
        gridIndex: 1,
        type: 'value',
        splitLine: {
          //show: false,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(200,200,200,1)', //里面横着的虚线
          },
        },
        axisTick: {
          show: false,
        },
        // data: SerData,
        axisLabel: {
          textStyle: {
            color: '#fff',
            fontSize: 12,
          },
        },
        axisLine: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: LegData[0],
        type: 'bar',
        data: maxSerData,
        barWidth: '20px',
        itemStyle: {
          normal: {
            barBorderRadius: [50, 50, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              1,
              0,
              [
                {
                  offset: 0,
                  color: '#0085E8', // 0% 处的颜色
                },
              ],
              false,
            ),
          },
        },
        label: {
          normal: {
            show: true,
            formatter: '{c}',
            position: 'insideTop',
            textStyle: {
              color: '#fff',
              fontSize: 12,
            },
          },
        },
      },
      {
        name: LegData[1],
        type: 'bar',
        barGap: '-100%',
        barWidth: '20px',
        itemStyle: {
          color: 'rgba(0,0,0,0)',
          borderColor: '#2A71FD',
          padding: 0,
          normal: {
            barBorderRadius: [50, 50, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              1,
              0,
              [
                {
                  offset: 0,
                  color: 'rgba(220,239,255,1)', // 0% 处的颜色
                },
              ],
              false,
            ),
          },
        },
        label: {
          normal: {
            show: true,
            lineHeight: 12,
            formatter: '{c}',
            position: 'top',
            right: 0,
            textStyle: {
              // fontWeight:'bold',
              color: '#fff',
              fontSize: 12,
            },
          },
        },
        z: -10,
        data: XaAllData,
      },
      {
        name: 'Temperature',
        type: 'line',
        data: maxSerData,
        smooth: true,
        symbol: 'none',
      },
      {
        name: LegData[0],
        type: 'bar',
        data: minSerData,
        barWidth: '20px',
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: {
          normal: {
            barBorderRadius: [50, 50, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              1,
              0,
              [
                {
                  offset: 0,
                  color: '#0085E8', // 0% 处的颜色
                },
              ],
              false,
            ),
          },
        },
        label: {
          normal: {
            show: true,
            formatter: '{c}',
            position: 'insideTop',
            textStyle: {
              color: '#fff',
              fontSize: 12,
            },
          },
        },
      },
      {
        name: LegData[1],
        type: 'bar',
        barGap: '-100%',
        barWidth: '20px',
        xAxisIndex: 1,
        yAxisIndex: 1,
        itemStyle: {
          color: 'rgba(0,0,0,0)',
          borderColor: '#2A71FD',
          padding: 0,
          normal: {
            barBorderRadius: [50, 50, 0, 0],
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              1,
              0,
              [
                {
                  offset: 0,
                  color: 'rgba(220,239,255,1)', // 0% 处的颜色
                },
              ],
              false,
            ),
          },
        },
        label: {
          normal: {
            show: true,
            lineHeight: 12,
            formatter: '{c}',
            position: 'top',
            right: 0,
            textStyle: {
              // fontWeight:'bold',
              color: '#fff',
              fontSize: 12,
            },
          },
        },
        z: -10,
        data: XaAllData,
      },
      {
        name: 'Temperature',
        type: 'line',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: minSerData,
        smooth: true,
        symbol: 'none',
      },
    ],
    barCategoryGap: '40%',
  };
  dom.setOption(option);
  addEventListener('resize', () => {
    dom.resize();
  });
};
</script>

<style lang="scss" scoped>
@mixin customStyle {
  border-radius: 10px;
  margin: 10px;
}
.main {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  .top {
    padding: 20px 20px 10px;
    // display: flex;
    @include customStyle;
    .left {
      flex: 3;
    }
    .right {
      margin-left: 40px;
      flex: 2;
    }
  }
}

#bar-chart {
  width: 99%;
  height: 75vh;
  padding: 40px;
  @include customStyle;
  background: rgba(0, 0, 0, 0.2);
}
</style>
